package restclient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;


public class AsyncRestClient extends AsyncTask<BasicNameValuePair, Void, JSONObject> {
	
	private Context context;
	private ProgressDialog progressDialog;
	private String errorMessage;
	
	
	//Start Listener
	private OnReceiveDataListener onReceiveDataListener;
	
	public void setOnReceiveDatalistener(OnReceiveDataListener listener){
		this.onReceiveDataListener = listener;
	}
	
	private void receiveData(JSONObject json){
		if(onReceiveDataListener != null) {
			try {
				onReceiveDataListener.onReceiveData(json);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	// End Listener
	
	public AsyncRestClient(Context c) {
		
		context = c;
		errorMessage  = "";
		progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		//progressDialog.setTitle(R.string.arc_progress_title);
		//progressDialog.setMessage(context.getText(R.string.arc_progress_message));
		progressDialog.setCancelable(false);
		
	}
	
	protected void onPreExecute(){
		
		super.onPreExecute();
		Log.e("======= ARC =======>>", "preExecute");
	}
	
	protected void onPostExecute(JSONObject result){
		
		super.onPostExecute(result);
		Log.e("======= ARC =======>>", "postExecute");
		
		progressDialog.dismiss();
		/*if(!errorMessage.isEmpty()){
			Toast.makeText(context, errorMessage,Toast.LENGTH_SHORT).show();
		}*/
		receiveData(result);
	}

	@Override
	protected JSONObject doInBackground(BasicNameValuePair... params) {
		// TODO Auto-generated method stub
		Log.e("======= ARC =======>>", "doInBackground");
		
		JSONObject result = new JSONObject();
		String http_url = "";
		String http_method = "";
		String query = "";
		Boolean first  = true;
		
		for(BasicNameValuePair pair : params){
			
			if(pair.getName().equalsIgnoreCase("http_url")){
				http_url = pair.getValue();
				continue;
			}
			
			if(pair.getName().equalsIgnoreCase("http_method")){
				http_method = pair.getValue();
				continue;
			}
			
			// key=value&key=value.....
			
			if(first){
				first = false;
			} else {
				query += "&";
			}
			
			try {			
			 query += URLEncoder.encode(pair.getName(), "UTF-8") + "=" + URLEncoder.encode(pair.getValue(), "UTF-8");
			} catch (UnsupportedEncodingException e){	
				//errorMessage = context.getString(R.string.arc_error_url);
				e.printStackTrace();
			}
		}
		Log.e("======== ARC ========>>", "URL : " + http_url);
		Log.e("======== ARC ========>>", "methode : " + http_method);
		Log.e("======== ARC ========>>", "query : " + query);
		
		
		try {
	
			URL url = (http_method.equalsIgnoreCase("GET"))?new URL(http_url + "/?" + query):new URL(http_url);
			HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
			
			connexion.setRequestMethod(http_method);
			connexion.setRequestProperty("Content-Type", "application/json");
			connexion.setInstanceFollowRedirects(false);
			connexion.setUseCaches(false);
			
			
			if(!http_method.equalsIgnoreCase("GET")) {
				connexion.setDoInput(true);
				connexion.setDoOutput(true);
		
				
				DataOutputStream dataOutputStream= new DataOutputStream(connexion.getOutputStream());
				dataOutputStream.writeBytes(query);
				dataOutputStream.flush();
				dataOutputStream.close();
			}
			InputStream is = connexion.getInputStream();
			String isString = convertStreamToString(is);
			result          = new JSONObject(isString);
				
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			//errorMessage = context.getString(R.string.arc_error_url);
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//errorMessage = context.getString(R.string.arc_error_connexion);
			e.printStackTrace();
		} catch(JSONException e) {
			//errorMessage = context.getString(R.string.arc_error_json);
			e.printStackTrace();
		}
		
		return result;
	}

	private String convertStreamToString(InputStream is) {
		// TODO Auto-generated method stub
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
		StringBuffer stringBuffer     = new StringBuffer();
		String line					  = null;
		
		try {
			while((line = bufferedReader.readLine()) != null) {
				stringBuffer.append(line + "\n");
				if(!bufferedReader.ready()) {
					break;
				}
			}		
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try{
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return stringBuffer.toString();
	}
	
	
	
}
